const express = require("express");
const router = express.Router();
const { login } = require("../controller/user");
const { SuccessMessageModel, ErrorMessageModel } = require("../model/reModel");
const {
  getArticleList,
  getArticleDetail,
  addArticle,
  updateArticle,
  deleteArticle,
} = require("../controller/blog");
const loginCheck = require("../middleware/loginCheck");

// TODO 这里可以在拆分一下写 把每一个不同的接口拆分到不同的文件夹下面

/**
 * 登陆
 */
router.use("/login", (req, res, next) => {
  const { username, password } = req.body;
  let result = login(username, password);
  return result.then((data) => {
    console.log("data=====", data);

    if (data.username) {
      // 设置session
      console.log("req.session====>", req.session);
      req.session.username = data.username;
      req.session.realname = data.realname;
      // res.setHeader("Access-Control-Allow-Credentials", true)
      res.json(new SuccessMessageModel({ type: data.type }, "登陆成功"));
      return;
    }
    res.json(new ErrorMessageModel(null, "账号或密码错误，请重新填写!"));
  });
});

/**
 * 新增文章
 */
router.post("/addArticle", loginCheck, (req, res, next) => {
  // loginCheck 是校验登陆的中间件
  const { id, keyWord } = req.body;
  console.log("author, keyword", id, req.body, req.params);
  let result = addArticle(id, keyWord);
  return result.then((listData) => {
    res.json(new SuccessMessageModel(listData, "查询成功"));
  });
});

/**
 * 文章列表
 */
router.post("/articleList", loginCheck, (req, res, next) => {
  req.body.author = req.session.username;
  const { id, keyWord } = req.body;
  let result = getArticleList(id, keyWord);

  return result.then((listData) => {
    res.json(new SuccessMessageModel(listData, "查询成功"));
  });
});

/**
 * 查询文章详情
 */
router.post("/articleDetail", loginCheck, (req, res, next) => {
  const { id, keyWord } = req.body;
  console.log("author, keyword", id, req.body, req.params);

  let result = getArticleDetail(id, keyWord);

  return result.then((listData) => {
    res.json(new SuccessMessageModel(listData, "查询成功"));
  });
});

// 删除文章
router.post("/articleDetail", loginCheck, (req, res, next) => {
  const { id, keyWord } = req.body;
  console.log("author, keyword", id, req.body, req.params);
  let result = deleteArticle(id, keyWord);
  return result.then((listData) => {
    res.json(new SuccessMessageModel(listData, "查询成功"));
  });
});

/**
 * 上传图片
 */
router.post("/upload", (req, res, next) => {});

module.exports = router;
